<template>
    <div class="page-container">
      <!-- 顶部标题栏 -->
      <header class="header">
        <BackBtn />
        <h1>举报详情</h1>
        <Time />
      </header>
  
      <div class="detail-content">
        <!-- 内容区 -->
        <section class="info-section">
          <h2>
            举报内容
            <span v-if="detail.report.reportType">【{{ detail.report.reportType }}】</span>
          </h2>
          <div class="info-item" v-if="detail.report.reportType==='实名举报'"><label>举报人姓名：</label><span>{{ detail.report.reporterName }}</span></div>
          <div class="info-item" v-if="detail.report.reportType==='实名举报'"><label>举报人身份证号：</label><span>{{ detail.report.reporterIdCard }}</span></div>
          <div class="info-item" v-if="detail.report.reportType==='实名举报'"><label>举报人手机号：</label><span>{{ detail.report.reporterPhone }}</span></div>
          <div class="info-item" v-if="detail.report.reportType==='实名举报'"><label>举报人联系地址：</label><span>{{ detail.report.reporterAddress }}</span></div>
          <div class="info-item"><label>被反映人姓名：</label><span>{{ detail.report.reportedPerson }}</span></div>
          <div class="info-item"><label>被反映人单位：</label><span>{{ detail.report.reportedUnit }}</span></div>
          <div class="info-item"><label>提交时间：</label><span>{{ formatDateTime(detail.report.submitTime) }}</span></div>
          <div class="info-item"><label>举报人选择的标签：</label><span>{{ formatTags(detail.report.tags) }}</span></div>
          <div class="info-item"><label>主要反映问题：</label><span>{{ detail.report.mainIssue }}</span></div>
          <div class="info-item"><label>分管部门：</label><span>{{ detail.report.department }}</span></div>
        </section>
  
        <!-- 图片预览区 -->
        <!-- <section class="image-preview" v-if="imageFiles.length > 0">
          <h3>图片附件预览</h3>
          <div class="image-gallery">
            <div class="image-item" v-for="file in imageFiles" :key="file.fileId" @click="openImagePreview(file.filePath)">
              <img :src="file.filePath" :alt="file.fileName" />
              <div class="image-caption">{{ file.fileName }}</div>
            </div>
          </div>
        </section> -->
  
        <!-- 附件区 -->
        <section class="attachments">
          <div class="attachment-group" v-if="imageFiles.length > 0">
            <h3>图片附件</h3>
            <div
              class="attachment-item"
              v-for="file in imageFiles"
              :key="file.fileId"
            >
              <div class="file-icon">
                <el-icon><Picture /></el-icon>
              </div>
              <div class="file-info">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-size">{{ formatSize(file.fileSize) }}</div>
              </div>
              <div class="file-actions">
                <el-button type="success" size="small" @click="handleDownloadSingleFile(file)" :loading="downloadingFiles[file.fileId]">
                  <el-icon><Download /></el-icon>下载
                </el-button>
              </div>
            </div>
          </div>
  
          <div class="attachment-group" v-if="videoFiles.length > 0">
            <h3>视频附件</h3>
            <div
              class="attachment-item"
              v-for="file in videoFiles"
              :key="file.fileId"
            >
              <div class="file-icon">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="file-info">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-size">{{ formatSize(file.fileSize) }}</div>
              </div>
              <div class="file-actions">
                <el-button type="success" size="small" @click="handleDownloadSingleFile(file)" :loading="downloadingFiles[file.fileId]">
                  <el-icon><Download /></el-icon>下载
                </el-button>
              </div>
            </div>
          </div>
  
          <div class="attachment-group" v-if="otherFiles.length > 0">
            <h3>其它补充附件</h3>
            <div
              class="attachment-item"
              v-for="file in otherFiles"
              :key="file.fileId"
            >
              <div class="file-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="file-info">
                <div class="file-name">{{ file.fileName }}</div>
                <div class="file-size">{{ formatSize(file.fileSize) }}</div>
              </div>
              <div class="file-actions">
                <el-button type="success" size="small" @click="handleDownloadSingleFile(file)" :loading="downloadingFiles[file.fileId]">
                  <el-icon><Download /></el-icon>下载
                </el-button>
              </div>
            </div>
          </div>
        </section>
  
        <!-- 下载所有内容与附件 -->
        <div class="action-buttons-container">
          <el-button type="danger" @click="handleDownloadAll" :loading="isDownloading">
            {{ isDownloading ? '正在导出...' : '下载内容以及附件' }}
          </el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { getReportDetail, downloadFile } from '@/api/report.js'
  import { ElMessage } from 'element-plus'
  import Time from '@/components/Time.vue'
  import BackBtn from '@/components/Back-btn.vue'
  import JSZip from 'jszip'
  import { saveAs } from 'file-saver'
  import { Document as DocxDocument, Paragraph, TextRun, Packer } from 'docx'
  import { Picture, Document, VideoPlay, Download } from '@element-plus/icons-vue'
  
  const route = useRoute()
  const detail = ref({ report: {}, files: [] })
  const isDownloading = ref(false)
  const downloadingFiles = ref({}) // 跟踪单个文件的下载状态
  
  // 预处理不同类型附件 - 注意这里使用 fileType 而不是 type
  const imageFiles = computed(() => detail.value.files.filter(file => file.fileType === 'image'))
  const videoFiles = computed(() => detail.value.files.filter(file => file.fileType === 'video'))
  const otherFiles = computed(() => detail.value.files.filter(file => file.fileType === 'other'))
  
  // 格式化标签
  const formatTags = (tags) => {
    if (!tags) return '无'
    
    // 标签映射
    const tagMap = {
      'bribery': '行贿受贿嫌疑',
      'dereliction': '渎职嫌疑',
      'lifestyle': '生活作风问题',
      'other': '其它'
    }
    
    return tags.split(',').map(tag => tagMap[tag] || tag).join(', ')
  }
  
  // 格式化日期时间
  const formatDateTime = (dateTimeStr) => {
    if (!dateTimeStr) return ''
    
    try {
      const date = new Date(dateTimeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
    } catch (e) {
      return dateTimeStr
    }
  }
  
  // 附件大小格式化 - 这里假设后端返回的大小单位是KB
  const formatSize = (size) => {
    if (size === undefined || size === null) return ''
    
    if (size < 1024) return size + 'KB'
    return (size / 1024).toFixed(2) + 'MB'
  }
  
  // 获取举报详情
  const fetchDetail = async () => {
    try {
      const res = await getReportDetail(route.params.reportId)
      if (res.code === 200) {
        detail.value = res.data
      } else {
        throw new Error(res.message || '获取数据失败')
      }
    } catch (err) {
      console.error('获取举报详情失败', err)
      ElMessage.error('获取举报详情失败，请重试')
    }
  }
  
  // 生成Word文档
  const generateWordDocument = async () => {
    try {
      const report = detail.value.report
      
      // 创建文档
      const doc = new DocxDocument({
        sections: [{
          properties: {},
          children: [
            new Paragraph({
              children: [
                new TextRun({
                  text: "举报详情",
                  bold: true,
                  size: 32,
                }),
              ],
              spacing: { after: 400 },
            }),
            // 基本信息
            new Paragraph({
              children: [new TextRun({ text: `举报类型：${report.reportType || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            
            // 实名举报才展示的字段
            ...(report.reportType === '实名举报' ? [
              new Paragraph({
                children: [new TextRun({ text: `举报人姓名：${report.reporterName || '无'}`, size: 24 })],
                spacing: { after: 200 },
              }),
              new Paragraph({
                children: [new TextRun({ text: `举报人身份证号：${report.reporterIdCard || '无'}`, size: 24 })],
                spacing: { after: 200 },
              }),
              new Paragraph({
                children: [new TextRun({ text: `举报人手机号：${report.reporterPhone || '无'}`, size: 24 })],
                spacing: { after: 200 },
              }),
              new Paragraph({
                children: [new TextRun({ text: `举报人联系地址：${report.reporterAddress || '无'}`, size: 24 })],
                spacing: { after: 200 },
              }),
            ] : []),
            
            new Paragraph({
              children: [new TextRun({ text: `被反映人姓名：${report.reportedPerson || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: `被反映人单位：${report.reportedUnit || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: `提交时间：${formatDateTime(report.submitTime) || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: `举报人选择的标签：${formatTags(report.tags) || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            
            // 举报内容
            new Paragraph({
              children: [
                new TextRun({
                  text: "主要反映问题：",
                  bold: true,
                  size: 24,
                }),
              ],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: report.mainIssue || '无', size: 24 })],
              spacing: { after: 400 },
            }),
            
            // 分管部门
            new Paragraph({
              children: [new TextRun({ text: `分管部门：${report.department || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            
            // 附件信息
            new Paragraph({
              children: [
                new TextRun({
                  text: "附件信息：",
                  bold: true,
                  size: 24,
                }),
              ],
              spacing: { after: 200 },
            }),
            
            // 列出所有附件
            ...detail.value.files.map((file, index) => 
              new Paragraph({
                children: [
                  new TextRun({ 
                    text: `${index + 1}. ${file.fileName} (${formatSize(file.fileSize)})`, 
                    size: 24 
                  })
                ],
                spacing: { after: 100 },
              })
            ),
          ],
        }],
      })

      // 生成Word文档
      const blob = await Packer.toBlob(doc)
      return blob
    } catch (error) {
      console.error('生成Word文档失败:', error)
      throw error
    }
  }

  // 下载文件的函数（可能需要修改为适配你的API）
  const downloadReportFile = async (url) => {
    try {
      const response = await downloadFile(url)
      return response
    } catch (error) {
      console.error(`下载文件失败: ${url}`, error)
      throw error
    }
  }

  // 下载所有内容与附件
  const handleDownloadAll = async () => {
    try {
      isDownloading.value = true
      ElMessage.info('正在准备下载文件，请稍候...')
      
      // 1. 生成Word文档
      const wordDoc = await generateWordDocument()
      
      // 2. 如果有附件，打包成zip
      if (detail.value.files && detail.value.files.length > 0) {
        const zip = new JSZip()
        
        // 添加Word文档到zip
        zip.file(`举报详情.docx`, wordDoc)
        
        // 文件夹分类
        const folderMap = {
          'image': '图片附件',
          'video': '视频附件',
          'other': '其他附件'
        }
        
        // 下载并添加所有附件
        for (const file of detail.value.files) {
          try {
            // 获取文件分类文件夹
            const folderName = folderMap[file.fileType] || '其他附件'
            
            // 下载文件（这里假设你有一个下载文件的API）
            const fileData = await downloadReportFile(file.filePath)
            
            // 添加到对应文件夹
            zip.file(`${folderName}/${file.fileName}`, fileData)
          } catch (err) {
            console.error(`添加文件到压缩包失败: ${file.fileName}`, err)
            ElMessage.warning(`文件 ${file.fileName} 下载失败，将被跳过`)
          }
        }
        
        // 生成zip文件并下载
        const content = await zip.generateAsync({ type: 'blob' })
        saveAs(content, `举报详情_${route.params.reportId}_附件.zip`)
      } else {
        // 如果没有附件，只下载Word文档
        saveAs(wordDoc, `举报详情_${route.params.reportId}.docx`)
      }
      
      ElMessage.success('下载完成！')
    } catch (error) {
      console.error('下载失败:', error)
      ElMessage.error('下载失败，请重试')
    } finally {
      isDownloading.value = false
    }
  }
  
  // 下载单个文件
  const handleDownloadSingleFile = async (file) => {
    // 防止重复点击
    if (downloadingFiles.value[file.fileId]) {
      return
    }
    
    try {
      downloadingFiles.value[file.fileId] = true
      const fileData = await downloadFile(file.filePath)
      saveAs(fileData, file.fileName)
      ElMessage.success('下载成功！')
    } catch (error) {
      console.error(`下载文件失败: ${file.fileName}`, error)
      ElMessage.error('下载失败，请重试')
    } finally {
      downloadingFiles.value[file.fileId] = false
    }
  }
  
  onMounted(fetchDetail)
  </script>
  
  <style scoped>
  @import '@/assets/css/detailAll/detail.css';
  @import '@/assets/css/detailAll/image.css';
  @import '@/assets/css/detailAll/attachment.css';
  
  /* 修改按钮容器样式 */
  .action-buttons-container {
    text-align: center;
    margin: 30px 0;
  }
  
  .el-button {
    height: 50px;
    border-radius: 10px;
    width: 180px;
    font-size: 16px;
    background-color: #d32f2f;
    border: none;
  }

  /* 按钮悬停样式 */
  .el-button:hover {
    background-color: #b62424;
    border: none;
  }


  </style>
  